#include "RenderCall.hpp"

using namespace Typhoon;

RenderCall::RenderCall() {
	maxVertices = 10000;
	maxTriangles = 10000;
	for (int i=0; i<maxVertices; i++) {
		vertices.push_back(Vertex());
	}
	for (int i=0; i<maxTriangles; i++) {
		triangles.push_back((GLshort)0);
	}
	Reset();
}

RenderCall::~RenderCall() {
}

void RenderCall::Reset() {
	verticesIndex = 0;
	trianglesIndex = 0;
	texture = 0;
}

bool RenderCall::RenderSprite(const Matrix4x4& world, Mesh& mesh, Texture* texture ) {
	if (verticesIndex>0 && this->texture!=texture) return false;

	const Mesh::VerticesList& sourceVertices = mesh.ReadOnlyVertices();
	int sourceVerticesSize = sourceVertices.size();
	
	if (verticesIndex+sourceVerticesSize>maxVertices) return false;

	const Mesh::TrianglesList& sourceTriangles = mesh.ReadOnlyTriangles();
	int sourceTrianglesSize = sourceTriangles.size();

	if (trianglesIndex+sourceTrianglesSize>maxTriangles) return false;

	this->texture = texture;
	
	
	int count = verticesIndex;
	for (int i=0; i<sourceVerticesSize; i++) {
		const Vertex& vertex = sourceVertices[i];
		Vertex& dest = vertices[verticesIndex++];
		//world.TransformPointRef2(dest.Position, vertex.Position);

		dest.Position = world.TransformPosition(vertex.Position);

		dest.TextureCoords = vertex.TextureCoords;
		dest.Color = vertex.Color;
		dest.Normal = world.TransformVector(vertex.Normal);
	}

	for (int i=0; i<sourceTrianglesSize; i++) {
		triangles[trianglesIndex++] = ((GLshort)(count + sourceTriangles[i]));
	}

	return true;
}

void RenderCall::Render() {

	if (vertices.empty()) return;

	if (!texture) {
		glBindTexture(GL_TEXTURE_2D,0);
	} else {
		glBindTexture(GL_TEXTURE_2D, texture->GetHandle());
	}

	glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &vertices[0].Position.x);
	glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &vertices[0].Color.r);
	glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &vertices[0].TextureCoords.x);
	glNormalPointer(GL_FLOAT, sizeof(Vertex), &vertices[0].Normal.x);

	//glDrawArrays(GL_QUADS, 0, 8);
	//glDrawElements(GL_TRIANGLES, vertices.size(), GL_UNSIGNED_SHORT, &indices[0]);
	//glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
	glDrawElements(GL_TRIANGLES, trianglesIndex, GL_UNSIGNED_SHORT, &triangles[0]);

	//glDrawRangeElements(GL_TRIANGLES, x, y, z, GL_UNSIGNED_SHORT, index);


}